package com.concurrent.config;

import com.concurrent.dao.RoleMapper;
import com.concurrent.dao.UserMapper;
import com.concurrent.dao.UserRoleMapper;
import com.concurrent.model.Role;
import com.concurrent.model.User;
import com.concurrent.model.UserRole;
import com.concurrent.service.UserService;
import com.concurrent.shiro.IShiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    IShiro shiroFactroy;
    @Autowired
    RoleMapper roleMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("————权限认证————");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String>  roleList  = shiroFactroy.getRoles(username);
        //获得该用户角色
        Set<String> set = new HashSet<>();
        for (String roleName: roleList){
            //需要将 role 封装到 Set 作为 info.setRoles() 的参数
            set.add(roleName);
        }
        //设置该用户拥有的角色
        info.setRoles(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————身份认证方法————");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 从数据库获取对应用户名密码的用户
        User  user  = shiroFactroy.user(token.getUsername());
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
